﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using Klaus.Bootloader.Properties;

namespace Klaus.Bootloader
{
    public partial class frmMain : Form
    {
        private svnloder svn;
        private Thread ts;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            label1.Text = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            ts = new Thread(new ThreadStart(Do));
            ts.Start();
        }

        private void Do()
        {
            try
            {
                svn = new svnloder(lblInfo);

                if (svn.Init())
                {
                    svn.ShowInfo("正在检查新版本....");
                    if (svn.CheckVer())
                    {
                        svn.ShowInfo("准备更新....");
                        svn.Update();
                    }
                }
                svn.ShowInfo("正在启动应用程序....");
                var psi =
                    new ProcessStartInfo(svn.GetAppLoc() + "\\" + Settings.Default.appname) { UseShellExecute = true };
                Process.Start(psi);
                Thread.Sleep(new TimeSpan(0, 0, 1));
            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker)delegate
                                       {
                                           TopMost = false;
                                           MessageBox.Show(string.Format("{0}\r\n 如果多次出现此问题，请联系客服人员", ex.Message));
                                       });
            }
            finally
            {
                svn = null;
            }
            Application.Exit();
        }

        private void frmMain_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Alt && e.Control &&
                e.KeyCode == Keys.Down)
            {
                TopMost = false;
                btnCancel.Visible = true;
                btnUpdate.Visible = true;
                txtver.Visible = true;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            svnloder.Cancel = true;
            if (ts != null)
            {
                ts.Abort();
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            int s;
            if (int.TryParse(txtver.Text, out s))
            {
                if (MessageBox.Show(string.Format("是否更新至{0}", s.ToString()), "更新至版本", MessageBoxButtons.OKCancel) ==
                    DialogResult.OK)
                {
                    svn.Update(s);
                }
            }
        }
    }
}